package com.ia.aistream.manager.operating.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.spring.SpringUtils;
import com.ia.aistream.manager.framework.util.ShiroUtils;
import com.ia.aistream.manager.operating.conf.DocMapConf;
import com.ia.aistream.manager.operating.util.convert.DocHandleBusiness;
import com.ia.aistream.manager.operating.util.convert.ShowSpeicalUtil;
import com.ia.aistream.manager.operating.util.style.DocStyleUtil;
import com.ia.aistream.manager.operating.util.tools.DocToolUtil;
import com.ia.aistream.mapper.operating.*;
import com.ia.aistream.model.operating.dto.ParagraphTextStyle;
import com.ia.aistream.model.operating.dto.convert.ConvertDto;
import com.ia.aistream.model.operating.dto.convert.EquOperInfo;
import com.ia.aistream.model.operating.entity.*;
import com.spire.doc.*;
import com.spire.doc.collections.DocumentObjectCollection;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.collections.TableCollection;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;


/**
 * @Author xiaoyu
 * @create 2020/12/15 18:29
 */
@Slf4j
public class DocFileData {
    /***
     * 获取整个文档的需要信息
     * 记录图片的位置，通过转换HTML 获得图片
     * @param fileName
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getDocFileData(String fileName,String ext) throws Exception {
        // 创建Word文档对象，加载整个文档数据
        Document doc = new Document();
        doc.loadFromFile(fileName);

        // 获取文档主信息的Mapper对象
        DocIndexMapper docIndexMapper = SpringUtils.getBean("docIndexMapper");
        Map<String, Object> map = new HashMap<>();
        Long fid = null;
        int imgNum = 0;
        int pageFlag = 0;
        int titleIndex = 0;
        int appParIndex = 1;
        String tName = fileName;

        // 获取文档数据
        SectionCollection sections = doc.getSections();
        // 获取文章的最大章节数
        int count = sections.getCount();
        // 遍历整个文档对象
        for(int i=0; i<count; i++){
            // 处理文档主信息
            if(i == 0){
                // 获取文件主信息
                Map<String, Object> indexMap = DocIndex.docIndex(sections.get(i), fileName,ext, imgNum);
                imgNum = (int) indexMap.get(DocMapConf.DOC_IMG_NUM.value);
                com.ia.aistream.model.operating.entity.DocIndex docIndex = (com.ia.aistream.model.operating.entity.DocIndex) indexMap.get(DocMapConf.DOC_INDEX.value);
                // 给对象的通用属性赋值
                docIndex.setCreateBy(ShiroUtils.getLoginName());
                docIndex.setCreateTime(new Date());

                // 将主信息保存到数据库
                docIndexMapper.insert(docIndex);
                fid = docIndex.getId();
                // 给对象的属性赋值
                DocApproval docApproval = (DocApproval) indexMap.get(DocMapConf.DOC_INDEX_APPROVAL.value);
                docApproval.setCreateBy(ShiroUtils.getLoginName());
                docApproval.setCreateTime(new Date());
                docApproval.setDocIndexId(fid);
                map.put(DocMapConf.DOC_INDEX_APPROVAL.value, docApproval);
            }else if(i == 1){
                // 获取规程修改跟踪信息
                Map<String, Object> revList = DocIndex.docTracking(sections.get(i), fid, fileName, ext, imgNum, titleIndex, appParIndex);
                if(revList.containsKey("titleIndex")){
                    titleIndex = (int) revList.get("titleIndex");
                }
                if(revList.containsKey("appParIndex")){
                    appParIndex = (int) revList.get("appParIndex");
                }
                map.putAll(revList);
            }else{
                // 获取段落数据
                Object o = map.get(DocMapConf.DOC_PARAGRAPH_List.value);
                // 获取表格数据
                Object t = map.get(DocMapConf.DOC_TABLE_LIST.value);
                // 获取附录表格数据
                Object app = map.get(DocMapConf.DOC_APPENDIX.value);
                // 获取附录段落数据
                Object appPar =null;
                if(map.containsKey(DocMapConf.DOC_APPENDIX_PAR_LiST.value)){
                    appPar = map.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value);
                }

                // 获取表格和段落内容
                Map<String, Object> tableOrParagraph = tableOrParagraph(sections.get(i), 0, fid, o, t, app, fileName, imgNum, tName, pageFlag, appPar, titleIndex, appParIndex);
                if(tableOrParagraph.containsKey("pageFlag")){
                    pageFlag = (int) tableOrParagraph.get("pageFlag");
                }
                titleIndex = (int) tableOrParagraph.get("titleIndex");
                appParIndex = (int) tableOrParagraph.get("appParIndex");
                tName = (String) tableOrParagraph.get("tName");
//                if(tableOrParagraph.containsKey(DocMapConf.DOC_APPENDIX_PAR_LiST.value)){
//                    docAppendixParagraphList.addAll((List<DocAppendixParagraph>) tableOrParagraph.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value));
//                }
                map.putAll(tableOrParagraph);
                if(tableOrParagraph.containsKey(DocMapConf.DOC_IMG_NUM.value)){
                    imgNum = (int) tableOrParagraph.get(DocMapConf.DOC_IMG_NUM.value);
                }
            }
        }
//        map.put(DocMapConf.DOC_APPENDIX_PAR_LiST.value, docAppendixParagraphList);
        return map;
    }


    /***
     * 获取段落和表格内容
     * @param sections
     * @param start 开始位置
     * @param fid  文件ID
     * @param parg  正文段落数据
     * @param t  正文表格数据
     * @param app  附录表格数据
     * @param fileName  文件名称
     * @param imgNum  图片顺序
     * @param tName  标题名称
     * @param pageFlag  分页数据
     * @param appPar 附录段落数据
     * @return
     * @throws Exception
     */
    public static Map<String,Object> tableOrParagraph(Section sections, int start, Long fid, Object parg, Object t, Object app,
                         String fileName, int imgNum, String tName, Integer pageFlag, Object appPar, int titleIndex, int appParIndex) throws Exception {

        Map<String,Object> map=new HashMap<>();
        int index=1;
        int tabIndex = 1;
        boolean tabFlag = false;
        String otherParId = null;
        boolean tabParFlag = false;
        String titleId = null;
        boolean subFlag = true;
        List<DocContentParagraph> list = new ArrayList<>();
        List<DocAppendix> docAppendixList = new ArrayList<>();
        List<DocContentTable> contentTableList = new ArrayList<>();
        List<DocAppendixParagraph> docAppendixParagraphList = new ArrayList<>();
        boolean flag = true;


        DocumentObjectCollection docs = sections.getBody().getChildObjects();
        int count = docs.getCount();
        for (int j = start; j < count; j++) {
            // 处理表格类型的数据
            if (docs.get(j).getDocumentObjectType().equals(DocumentObjectType.Table)){
//                if(!StringUtils.isEmpty(titleId) && titleId.equals("999")){
                if(tabFlag){
                    titleId = otherParId;
                    tabFlag = false;
                }
                Table table=(Table)docs.get(j);
                // 获取表格数据
                if(t==null){
                    t = map.get(DocMapConf.DOC_TABLE_LIST.value);
                }
                if(app==null){
                    // 获取附录数据
                    app = map.get(DocMapConf.DOC_APPENDIX.value);
                }
                // 获取表格的内容
                Map<String, Object> tables = tables(docs, table, fid, t, app, j, fileName, imgNum, tName, 0, pageFlag, titleId, appPar, tabIndex, titleIndex, appParIndex);
                if(tables.containsKey("pageFlag")){
                    pageFlag = (int) tables.get("pageFlag");
                }
                tabIndex = (int) tables.get("index");
                tName = (String) tables.get("tName");
                imgNum = (int) tables.get(DocMapConf.DOC_IMG_NUM.value);
                titleIndex = (int) tables.get("titleIndex");
                appParIndex = (int) tables.get("appParIndex");
                Object objId = tables.get("titleId");
                if(objId!=null){
                    titleId = (String)objId;
                    subFlag = false;
                    tabParFlag = true;
                }
                if(tables.containsKey(DocMapConf.DOC_APPENDIX.value)){
                    docAppendixList.addAll((List<DocAppendix>)tables.get(DocMapConf.DOC_APPENDIX.value));
                }
                if(tables.containsKey(DocMapConf.DOC_APPENDIX_PAR_LiST.value)){
                    docAppendixParagraphList.addAll((List<DocAppendixParagraph>)tables.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value));
                }
                if(tables.containsKey(DocMapConf.DOC_TABLE_LIST.value)){
                    contentTableList=(List<DocContentTable>) tables.get(DocMapConf.DOC_TABLE_LIST.value);
                }
//                map.put()
                map.putAll(tables);
                // 处理附录的后面还有其他类型的情况
                if(tables.containsKey("start")){
                    j = (int) tables.get("start");
                    if(j>=docs.getCount()){
                        break;
                    }
                }
            }else if (docs.get(j).getDocumentObjectType().equals(DocumentObjectType.Paragraph)){
                // 处理段落类型的数据
                Paragraph paragraph=(Paragraph)docs.get(j);
                String trim = paragraph.getText().trim();
                trim = trim.replace(" ", "");
                if(trim.equals("目录")){
                    flag = false;
                }else if(trim.startsWith("附录")){
                    flag=true;
                    continue;
                }else if(trim.equals("附表1：1号机组阴极保护系统运行操作单")){
                    if(docs.get(j+1).getDocumentObjectType().equals(DocumentObjectType.Table)){
                        Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, imgNum, fid, tName);
                        ParagraphTextStyle paragraphStyle = (ParagraphTextStyle) psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value);
                        imgNum = (int) psMap.get(DocMapConf.DOC_IMG_NUM.value);

                        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(paragraphStyle);
                        titleIndex++;
                        DocTitle docTitle = saveTitle(trim, fid, jsonObject, 5, titleIndex);
                        String tid = docTitle.getId();
                        Table table = (Table) docs.get(j+1);
                        DocOperationSheetUtil.getOperationStyle(table, tid);
                        j++;
                        continue;
                    }
                }
                // 处理表格中含有段落的情况
                if (tabParFlag){
                    DocTitleMapper docTitleMapper = SpringUtils.getBean("docTitleMapper");
                    DocTitle docTitle = docTitleMapper.selectDocTitleById(titleId);
                    Integer titleType = docTitle.getTitleType();
                    if(titleType==1 && j!=count-1){
                        // 插入新数据
                        DocContentTable docContentTable = new DocContentTable();
                        docContentTable.setStepNum(++tabIndex);
                        docContentTable.setId(DocToolUtil.getUUID());
                        docContentTable.setRowNum(0L);
                        docContentTable.setRowType(5);
                        docContentTable.setDocTitleId(titleId);
                        docContentTable.setCreateTime(new Date());
                        docContentTable.setCreateBy(ShiroUtils.getLoginName());
                        // 添加到集合中
                        contentTableList.add(docContentTable);
                        otherParId = titleId;
//                        otherParId = docContentTable.getId();
                        titleId = docContentTable.getId();
                        tabFlag = true;

                    }
                    tabParFlag = false;
                }
                ////////////////////////////////////---------------------
                if(flag){
                    // 查询段落中的数据
                    Map<String, Object> parMap = getParagraph(paragraph, fid, index, titleId, imgNum, fileName, tName, titleIndex);
                    if(parMap==null){
                        if(j<count-1){
                            if(docs.get(j+1).getDocumentObjectType().equals(DocumentObjectType.Table)){
                                Table table = (Table) docs.get(j+1);
                                // 表格的第一行超过一列
                                if(table.getRows().get(0).getCells().getCount()>1){
                                    // 处理子表数据
                                    DocContentParagraph docContentParagraph = new DocContentParagraph();
                                    docContentParagraph.setConType(3);
                                    docContentParagraph.setCreateBy(ShiroUtils.getLoginName());
                                    docContentParagraph.setCreateTime(new Date());
                                    docContentParagraph.setDocTitleId(titleId);
                                    docContentParagraph.setId(DocToolUtil.getUUID());
                                    docContentParagraph.setStepNum(index);
                                    index++;
                                    list.add(docContentParagraph);
                                    List<DocParagraphSub> paragraphSub = DocSubTableUtil.getParagraphSub(table, docContentParagraph.getId());
                                    DocParagraphSubMapper docParagraphSubMapper = SpringUtils.getBean("docParagraphSubMapper");
                                    docParagraphSubMapper.insertDocParagraphSubList(paragraphSub);
                                    j++;
                                }
                            }
                        }
                        continue;
                    }else if(parMap.containsKey("titleId")){
                        titleId = (String) parMap.get("titleId");
                        tName = (String)parMap.get("tName");
                        subFlag = true;
                        tabParFlag = false;
                        index=0;
                        titleIndex = (int) parMap.get("titleIndex");
                        continue;
                    }else if(parMap.containsKey(DocMapConf.DOC_PARAGRAPH_CONTENT.value)){
                        imgNum = (int) parMap.get(DocMapConf.DOC_IMG_NUM.value);
                        tName = (String)parMap.get("tName");
                        DocContentParagraph docContent = (DocContentParagraph) parMap.get(DocMapConf.DOC_PARAGRAPH_CONTENT.value);
                        index++;
                        subFlag = true;
                        list.add(docContent);
                        titleIndex = (int) parMap.get("titleIndex");
                    }
//                    titleIndex = (int) parMap.get("titleIndex");
                    if(j<count-1 && subFlag){
                        if(docs.get(j+1).getDocumentObjectType().equals(DocumentObjectType.Table)){
                            Table table = (Table) docs.get(j+1);
                            // 表格的第一行超过一列
                            if(table.getRows().get(0).getCells().getCount()>1){
                                // 处理子表数据
                                DocContentParagraph docContentParagraph = new DocContentParagraph();
                                docContentParagraph.setConType(3);
                                docContentParagraph.setCreateBy(ShiroUtils.getLoginName());
                                docContentParagraph.setCreateTime(new Date());
                                docContentParagraph.setDocTitleId(titleId);
                                docContentParagraph.setId(DocToolUtil.getUUID());
                                docContentParagraph.setStepNum(index);
                                index++;
                                list.add(docContentParagraph);
                                List<DocParagraphSub> paragraphSub = DocSubTableUtil.getParagraphSub(table, docContentParagraph.getId());
                                DocParagraphSubMapper docParagraphSubMapper = SpringUtils.getBean("docParagraphSubMapper");
                                docParagraphSubMapper.insertDocParagraphSubList(paragraphSub);
                                j++;
                            }
                        }
                    }
                }
            }
        }
        // 处理逻辑
        List<DocContentParagraph> result = new ArrayList<>();

        if(parg!=null){
            result = (List<DocContentParagraph>) parg;
        }
        result.addAll(list);
        map.put(DocMapConf.DOC_PARAGRAPH_List.value, result);
        map.put("tName", tName);
        map.put("pageFlag", pageFlag);
        if(docAppendixList.size()>0) {
//            if(map.containsKey(DocMapConf.DOC_APPENDIX.value)) {
//                docAppendixList.addAll((List<DocAppendix>) map.get(DocMapConf.DOC_APPENDIX.value));
//            }
            map.put(DocMapConf.DOC_APPENDIX.value, docAppendixList);
        }
        map.put(DocMapConf.DOC_TABLE_LIST.value, contentTableList);
        map.put(DocMapConf.DOC_APPENDIX_PAR_LiST.value, docAppendixParagraphList);
        map.put("titleIndex", titleIndex);
        map.put("appParIndex", appParIndex);
        return map;
    }

    /***
     * 获取段落对象
     * @param paragraph
     * @param fid
     * @param index
     * @param titleId
     * @param imgNum 表示图片的顺序
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Map<String, Object> getParagraph(Paragraph paragraph, Long fid, Integer index, String titleId, int imgNum, String fileName, String tName, int titleIndex) throws Exception {

        // 获取段落的内容
        String trim = paragraph.getText().trim();
        if(StringUtils.isEmpty(trim) && paragraph.getChildObjects().getCount()==0){
            return null;
        }
        Map<String,Object> map = new HashMap<>();
        DocContentParagraph docContentParagraph = new DocContentParagraph();
        // 获取段落样式
        Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, imgNum, fid, tName);
        imgNum = (int) psMap.get(DocMapConf.DOC_IMG_NUM.value);
        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);
        ParagraphTextStyle paragraphStyle = (ParagraphTextStyle) psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value);
        // 获取段落表格序号
        trim = (paragraph.getListText().trim() + "  " + trim).trim();
        // 获取段落转义后的数据
        ConvertDto paragraphConvert = DocHandleBusiness.getParagraphConvert(paragraph);
        // 判断是否为标题
        int title = DocStyleUtil.isTitle(paragraph);
        if(title==1){
            // 存储标题数据
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(paragraphStyle);
            titleIndex++;
            DocTitle docTitle = saveTitle(trim, fid, jsonObject, 0, titleIndex);
            titleId = docTitle.getId();
            tName = trim;
            map.put("titleId", titleId);
            map.put("tName", tName);
            map.put("titleIndex", titleIndex);
            return map;
        }else if(title==2){
            tName = trim;
            docContentParagraph.setConType(1);
        }else{
            docContentParagraph.setConType(0);
        }
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(paragraphStyle);
        ParagraphTextStyle paragraphTextStyle = jsonObject.toJavaObject(ParagraphTextStyle.class);
        // 实现将数据保存到数据库
        if(paragraphTextStyle!=null && paragraphTextStyle.getTextInfoList().size()>0 && titleId!=null){

            docContentParagraph.setDocTitleId(titleId);
//            docContentParagraph.setContent(URLEncoder.encode(trim, "UTF-8"));
            docContentParagraph.setContent(trim);
            docContentParagraph.setContentStyle(jsonObject);
            docContentParagraph.setStepNum(index);

            // 判断对象是否为空
            if(paragraphConvert!=null){
                docContentParagraph.setContentC(paragraphConvert.toString());
            }
            docContentParagraph.setCreateBy(ShiroUtils.getLoginName());
            docContentParagraph.setCreateTime(new Date());
            docContentParagraph.setId(DocToolUtil.getUUID());
            titleId = docContentParagraph.getDocTitleId();
        }
        map.put(DocMapConf.DOC_PARAGRAPH_CONTENT.value, docContentParagraph);
        map.put("tName", tName);
        map.put("titleIndex", titleIndex);
        if(StringUtils.isEmpty(titleId) || docContentParagraph.getId()==null){
            return null;
        }
        return map;
    }

    /**
     * 表格解析
     * @param docs 文档对象
     * @param table 表格对象
     * @param fid 文件ID
     * @param o
     * @param app
     * @param start 开始位置
     * @param fileName fileName文件名称
     * @param imgNum imgNum（图片的顺序）
     * @param tName （标题的名称）
     * @param startRow 开始的行
     * @param pageFlag 分页参数
     * @param titleId 标题Id
     * @return
     * @throws Exception
     */
    public static Map<String, Object> tables(DocumentObjectCollection docs, Table table, Long fid, Object o, Object app,
                                             int start, String fileName, int imgNum, String tName, int startRow, int pageFlag, String titleId, Object appPar, int index, int titleIndex, int appParIndex) throws Exception {

        Map<String, Object> map = new HashMap<>();
        List<DocContentTable>  resultTable = new ArrayList<>();
        // 记录附录表格信息
        List<DocAppendix> result = new ArrayList<>();
        // 记录附录段落数据
        List<DocAppendixParagraph> appendixParagraphList = new ArrayList<>();
        if(o!=null){
            resultTable = (List<DocContentTable>) o;
        }
        if(appPar!=null){
            appendixParagraphList.addAll((List<DocAppendixParagraph>)appPar);
        }
        boolean flag = false;
        // 获取
        String trim = table.getRows().get(startRow).getCells().get(0).getParagraphs().get(0).getText().trim();
//        Long titleId = 0L;
        String cellContent = DocIndex.getCellContent(table.getRows().get(startRow).getCells().get(0));

        if((trim.endsWith("附录") || trim.startsWith("附录")) && table.getRows().get(startRow).getCells().getCount()==1){
            if(app!=null){
                result.addAll((List<DocAppendix>) app);
            }

            // 处理附录以后的数据
            Map<String, Object> appendixData = DocAppendixUtil.getAppendixData(docs, tName, fileName, result, pageFlag, imgNum, fid, start, flag, titleId, startRow, titleIndex, appParIndex);
            pageFlag = (int) appendixData.get("pageFlag");
            imgNum = (int) appendixData.get(DocMapConf.DOC_IMG_NUM.value);
            tName = (String) appendixData.get("tName");
            start = (int) appendixData.get("start");
            titleIndex = (int) appendixData.get("titleIndex");
            appParIndex = (int) appendixData.get("appParIndex");
            map.put(DocMapConf.DOC_APPENDIX.value, result);
            // 存储段落内容数据
            appendixParagraphList.addAll((List<DocAppendixParagraph>)appendixData.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value));
        }else if(cellContent.equals("1  常见运行故障分析")){
            Paragraph paragraph = null;
            for (int i=0; i<table.getRows().get(0).getCells().get(0).getParagraphs().getCount(); i++){
                paragraph = table.getRows().get(0).getCells().get(0).getParagraphs().get(i);
                if(!StringUtils.isEmpty(paragraph.getText())){
                    break;
                }
            }

            Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, 0, fid, tName);
            JSONObject jsonObject = (JSONObject) JSON.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value));
            String titleName = paragraph.getListText() + "  " + paragraph.getText().trim();
            titleIndex++;
            DocTitle docTitle = saveTitle(titleName, fid, jsonObject, 2, titleIndex);
            titleId = docTitle.getId();
            tName = titleName;

            TableCollection tables = table.getRows().get(0).getCells().get(0).getTables();
            // 获取子表数据
            if (tables.getCount()>0){
                List<DocAppendix> subTableContent = DocSubTableUtil.getAppendixSubTableContent(tables, titleId);
                result.addAll(subTableContent);
            }
            map.put("pageFlag", pageFlag);
            map.put(DocMapConf.DOC_APPENDIX.value, result);
            map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);

        }else{
            // 处理表格中数据
            Map<String, Object> tableContent = getTableContent(docs, start, table, fid, fileName, tName, pageFlag, imgNum, titleId, index, titleIndex, appParIndex);

            resultTable.addAll((List<DocContentTable>)tableContent.get("docContentTableList"));

            map.put("titleId", tableContent.get("titleId"));
            index = (int) tableContent.get("index");
            titleIndex = (int) tableContent.get("titleIndex");
            appParIndex = (int) tableContent.get("appParIndex");
            // 处理附录数据
            if(tableContent.containsKey(DocMapConf.DOC_APPENDIX.value)){

                List<DocAppendix> o1 = (List<DocAppendix>) tableContent.get(DocMapConf.DOC_APPENDIX.value);
                map.put(DocMapConf.DOC_APPENDIX.value, o1);
            }
            if(tableContent.containsKey("pageFlag")){
                pageFlag = (int) tableContent.get("pageFlag");

            }
            tName = (String) tableContent.get("tName");
            if(tableContent.containsKey("start")){
                start = (int)tableContent.get("start");
            }
            if(tableContent.containsKey(DocMapConf.DOC_APPENDIX_PAR_LiST.value)){
                appendixParagraphList.addAll((List<DocAppendixParagraph>)tableContent.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value));
            }
        }

        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);
        map.put(DocMapConf.DOC_TABLE_LIST.value, resultTable);
        map.put("tName", tName);
        map.put("pageFlag", pageFlag);
        map.put("start", start);
        map.put(DocMapConf.DOC_APPENDIX_PAR_LiST.value, appendixParagraphList);
        map.put("index", index);
        map.put("titleIndex", titleIndex);
        map.put("appParIndex", appParIndex);

        return map;
    }




    /***
     * 获取表格中的数据,附录除外
     * @param table
     * @param fid 索引信息Id
     * @return
     * @throws UnsupportedEncodingException
     */
    private static Map<String, Object> getTableContent(DocumentObjectCollection docs, int start, Table table, Long fid, String fileName, String tName,
                                                       Integer pageFlag, int imgNum, String tid, int index, int titleIndex, int appParIndex) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<DocContentTable> list=new ArrayList<DocContentTable>();
        int cMax = DocStyleUtil.getColsMax(table, 0);

//        long tid = 0L;
        //处理标题行有多个字段的情况
        for (int i = 0; i < table.getRows().getCount(); i++) {
            int pt = 0;
            if (table.getRows().get(i).getCells().getCount() <= cMax){
                int count1 = table.getRows().get(i).getCells().get(0).getParagraphs().getCount();
                for(int p=0; p<count1; p++){
                    Paragraph paragraph = table.getRows().get(i).getCells().get(0).getParagraphs().get(p);
                    if(!StringUtils.isEmpty(paragraph.getText().trim())){
                        pt = p;
                        break;
                    }
                }
                DocContentTable tab=new DocContentTable();
                if (DocStyleUtil.isTitle(table.getRows().get(i).getCells().get(0).getParagraphs().get(pt))==1 && table.getRows().get(i).getCells().getCount()==1){
                    index = 1;

                    Paragraph paragraph = table.getRows().get(i).getCells().get(0).getParagraphs().get(pt);
                    // 获取标题名称
                    String titleName = paragraph.getListText().trim() + "  " + paragraph.getText().trim();
                    titleName = titleName.trim();
                    TableCollection tables = table.getRows().get(i).getCells().get(0).getTables();
                    /**
                     * 处理附录的情况
                     * **/
                    boolean appendix = DocRegularUtil.isAppendix(titleName);
                    if(appendix){
                        map.put("appFlag", true);
                        // 处理附录数据
                        Map<String, Object> appendixSource = getAppendixSource(docs, table, i, start, imgNum, fileName, tName, tid, fid, pageFlag, titleIndex, appParIndex);
                        titleIndex = (int) appendixSource.get("titleIndex");
                        appParIndex = (int) appendixSource.get("appParIndex");
                        map.putAll(appendixSource);
                        break;
                    }
                    // 获取标题样式
                    Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, 0, fid, tName);
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value));

                    int type = 1;
                    // 判断一下，下一行的数据是为表格
                    if(table.getRows().getCount()<2 && tables.getCount()==0){
                        type = 0;
                    }
                    index=1;
                    titleIndex++;
                    DocTitle docTitle = saveTitle(titleName, fid, jsonObject, type, titleIndex);
                    tid = docTitle.getId();
                    tName = titleName;
                    // 获取子表数据
                    if (tables.getCount()>0){
                        List<DocContentTable> subTableContent = DocSubTableUtil.getSubTableContent(tables, tid);
                        list.addAll(subTableContent);
                    }
                    continue;
                }else if(DocStyleUtil.isTitle(table.getRows().get(i).getCells().get(0).getParagraphs().get(0))==2 &&
                        !table.getRows().get(i).getCells().get(0).getParagraphs().get(0).getFormat().getHorizontalAlignment().toString().equals("Right")){
                    tab.setRowType(1);
                    tName =DocIndex.getCellContent(table.getRows().get(i).getCells().get(0)).trim();
                }else {
                    tab.setRowType(0);
                }

                // 行的列数
                tab.setRowNum((long)table.getRows().get(i).getCells().getCount());
                //循环列
                for (int j = 0; j <table.getRows().get(i).getCells().getCount() ; j++) {
                    TableCell tableCell = table.getRows().get(i).getCells().get(j);
                    // 处理列中的子表
                    TableCollection tables = tableCell.getTables();
                    if (tables.getCount()>0){
                        List<DocContentTable> subTableContent = DocSubTableUtil.getSubTableContent(tables, tid);
                        list.addAll(subTableContent);
                    }
                    // 获取单元格内容
                    String cellContent = DocIndex.getCellContent(tableCell).trim();

                    // 获取单元格样式
                    JSONObject columnStyle = DocStyleUtil.getColumnStyle(table, i, j);
                    if(columnStyle==null){
                        continue;
                    }

                    int underCount = 0;
                    if(columnStyle.toJSONString().contains("underLine")){
                        String[] split = columnStyle.toJSONString().split("underLine");
                        underCount = split.length - 1;
                    }
                    String convert = null;
                    // 获取单元格转义后数据
                    ConvertDto tableConvertContent = DocHandleBusiness.getTableConvertContent(tableCell, underCount);
                    if(tableConvertContent!=null){
                        convert = tableConvertContent.toString();
                        EquOperInfo eq_op = tableConvertContent.getEq_op();
                        if(eq_op!=null && !StringUtils.isEmpty(cellContent)){
                            columnStyle = ShowSpeicalUtil.show(cellContent, columnStyle, eq_op, "table");
                        }
                    }
                    tab.setId(DocToolUtil.getUUID());
                    tab.setStepNum(index);
                    tab.setDocTitleId(tid);
                    tab.setCreateBy(ShiroUtils.getLoginName());
                    tab.setCreateTime(new Date());
                    int flag = j;
                    if(table.getRows().get(i).getCells().getCount()==7 && j<3){
                        flag=j-1;
                    }else if(table.getRows().get(i).getCells().getCount()==7 && j>2){
                        flag = j-2;
                    }
                    String s = tableCell.getCellFormat().getVerticalMerge().toString();
                    if(s.equals("Continue")){
                        columnStyle = null;
                    }
                    switch (flag){
                        case 0:
                            tab.setC1O(cellContent);
                            tab.setC1Style(columnStyle);
                            tab.setC1C(convert);
                            break;
                        case 1:
                            tab.setC2O(cellContent);
                            tab.setC2Style(columnStyle);
                            break;
                        case 2:
                            tab.setC3O(cellContent);
                            tab.setC3Style(columnStyle);
                            tab.setC3C(convert);
                            break;
                        case 3:
                            tab.setC4O(cellContent);
                            tab.setC4Style(columnStyle);
                            tab.setC4C(convert);
                            break;
                        case 4:
                            tab.setC5O(cellContent);
                            tab.setC5Style(columnStyle);
                            tab.setC5C(convert);
                            break;
                        default:
                            log.error("正文表格解析失败" + j);
                            break;
                    }
                }
                list.add(tab);
            }else {
                cMax = DocStyleUtil.getColsMax(table, i);
                i--;
            }
            index ++;
        }

        map.put("docContentTableList", list);
        map.put("titleId", tid);
        map.put("tName", tName);
        map.put("index", index);
        map.put("titleIndex",  titleIndex);
        map.put("appParIndex", appParIndex);
        return map;
    }

    /***
     * 将标题信息存放到数据库，将插入的标题Id返回
     * @param titleName
     * @param fid
     * @param jsonObject
     * @param type
     * @return  返回标题的Id
     */
    public static DocTitle saveTitle(String titleName, Long fid, JSONObject jsonObject, Integer type, int titleIndex){

        // 获取docTitleMapper对象
        DocTitleMapper docTitleMapper = SpringUtils.getBean("docTitleMapper");

        if(titleName.equals("1.  条件")){
            titleName = "1.  基本条件";
        }
        // 根据标题名称来查询结果，有则获取Id trim(replace(title_name,' ',''))  in ('1.附录')
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("trim(replace(title_name,' ',''))", titleName.replace(" ", ""));
        queryWrapper.eq("doc_index_id", fid);
        List<DocTitle> selectList = docTitleMapper.selectList(queryWrapper);
        if(selectList.size()>0){
            return selectList.get(0);
        }
        // 将标题数据插入数据库
        DocTitle docTitle = new DocTitle();
        docTitle.setId(DocToolUtil.getUUID());
        docTitle.setTitleName(titleName);
        docTitle.setTitleType(type);
        docTitle.setDocIndexId(fid);
        docTitle.setStepNum(titleIndex);
        docTitle.setCreateBy(ShiroUtils.getLoginName());
        docTitle.setCreateTime(new Date());
        docTitle.setTitleNameStyle(jsonObject);
        docTitleMapper.insert(docTitle);

        return docTitle;
    }


    /***
     * 特殊情况下附录信息的解析
     * @param docs  文档章节对象
     * @param table 表格
     * @param startRow 开始行数
     * @param imgNum 图片顺序
     * @param fileName 文件名称
     * @param tName 标题名称
     * @param titleId 标题IId
     * @param fid 文件id
     * @param pageFlag 分页表示
     * @return  附录相关的对象
     * @throws Exception
     */
    public static Map<String, Object> getAppendixSource(DocumentObjectCollection docs, Table table, int startRow, int start, int imgNum,
                                        String fileName, String tName, String titleId, long fid, int pageFlag, int titleIndex,int appParIndex) throws Exception{

        Map<String, Object> map = new HashMap<>();
        List<DocAppendix> result = new ArrayList();
        boolean flag = false;
//        for (int r=startRow; r<table.getRows().getCount(); r++){
            String text = table.getRows().get(startRow).getCells().get(0).getParagraphs().get(0).getListText() + "  "
                    +  table.getRows().get(startRow).getCells().get(0).getParagraphs().get(0).getText();
            if (text.endsWith("附录")){

                Map<String, Object> appendixData = DocAppendixUtil.getAppendixData(docs, tName, fileName, result, pageFlag, imgNum, fid, start, flag, titleId, startRow, titleIndex, appParIndex);

                pageFlag = (int) appendixData.get("pageFlag");
//                result.addAll((List<DocAppendix>)appendixData.get(DocMapConf.DOC_APPENDIX.value));
                imgNum = (int) appendixData.get(DocMapConf.DOC_IMG_NUM.value);
                tName = (String) appendixData.get("tName");
                start = (int) appendixData.get("start");
                titleIndex = (int) appendixData.get("titleIndex");
                appParIndex = (int) appendixData.get("appParIndex");
                map.put(DocMapConf.DOC_APPENDIX_PAR_LiST.value, appendixData.get(DocMapConf.DOC_APPENDIX_PAR_LiST.value));


//                Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(table.getRows().get(startRow).getCells().get(0).getParagraphs().get(0), fileName, 0, fid, tName);
//                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value));
//
//                tid = saveTitle(text.trim(), fid, jsonObject, 4);
//
//                Map<String, Object> mapApp = DocIndex.getAppendixData(table, startRow, tid, fid, index, tName, pageFlag);
//                tName = (String) mapApp.get("tName");
//                if(mapApp.containsKey("titleId")){
//                    tid = (Long) mapApp.get("titleId");
//                }
//
//                if(mapApp.containsKey("appendixList")){
//                    result.addAll((List<DocAppendix>)mapApp.get("appendixList"));
//                    index = (int) mapApp.get("index");
//                }
//                if(mapApp.containsKey("pageFlag")){
//                    pageFlag = (int) mapApp.get("pageFlag");
//                }
            }

        map.put(DocMapConf.DOC_APPENDIX.value, result);
        map.put("pageFlag", pageFlag);
        map.put("imgName", imgNum);
        map.put("tName", tName);
        map.put("start", start);
        map.put("titleIndex", titleIndex);
        map.put("appParIndex", appParIndex);
        return map;
    }
}
